<template>
	<view class="file-page">
		<navView navTitle="资料上传" titleColor="#fff" :isBack="true"></navView>
		<!-- 顶部功能按钮 -->
		<view class="toolbar">
			<view class="button" @click="handleFileCollection">
				<image src="https://hfd.bjlzkj.com/static/upfile/xiang.png" alt="文件收集箱" class="icon"></image>
				文件收集箱
			</view>
			<view class="button" @click="handleDataLibrary">
				<image src="https://hfd.bjlzkj.com/static/upfile/zi.png" alt="资料库" class="icon"></image>
				资料库
			</view>
		</view>

		<!-- 文件列表 -->
		<view class="file-list">
			<view v-for="(file, index) in fileList" :key="index" class="file-item">
				<view class="file-name">
					<image src="https://hfd.bjlzkj.com/static/upfile/wen.png" alt="文件夹图标" class="folder-icon"></image>
					{{ file.filename }}
				</view>
				<view class="file-description">{{ file.filesize }}</view>
				<view class="flex">
					<view class="file-time">{{ file.createtime }}</view>
					<view class="file-actions">
						<view class="action1" @click="previewFile(file.url)">
							<image src="https://hfd.bjlzkj.com/static/upfile/cha.png" alt="预览" class="action-icon">
							</image>
							预览
						</view>
						<view class="action2" @click="downloadFile(file.url)">
							<image src="https://hfd.bjlzkj.com/static/upfile/xia.png" alt="下载" class="action-icon">
							</image>
							下载
						</view>
						<view v-if="category != 'category1'" class="action2" @click="confirmDelete(file.id, index)">
							<image src="https://hfd.bjlzkj.com/static/upfile/delete.png" alt="删除" class="action-icon">
							</image>
							删除
						</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 分页提示 -->
		<view v-if="isLoading" class="loading-text">加载中...</view>
		<view v-if="isNoMore && fileList.length > 0" class="no-more-text">已经到底啦~</view>
		<!-- 底部上传按钮 -->
		<image @click="uploadFile" class="addimg" src="https://hfd.bjlzkj.com/static/user/add.png" mode=""></image>
	</view>
</template>

<script>
import download from '@/util/filesdownload.js'; //
export default {
	data() {
		return {
			companyID: 0,
			currentPage: 1,
			totalPages: 1,
			isLoading: false,
			isNoMore: false,
			category: '',
			fileList: [], // 清空初始测试数据
		};
	},
	onLoad() {
		this.getFileList()
	},
	// 添加页面滚动监听
	onReachBottom() {
		if (!this.isNoMore) {
			this.getFileList();
		}
	},
	methods: {
		// 返回上一页
		goBack() {
			uni.navigateBack();
		},
		// 新增删除确认弹窗
		confirmDelete(fileId, index) {
			uni.showModal({
				title: '删除确认',
				content: '确定要删除这个文件吗？',
				success: (res) => {
					if (res.confirm) {
						this.deleteFile(fileId, index)
					}
				}
			})
		},
		// 新增删除接口调用
		async deleteFile(fileID, index) {
			uni.showLoading({ title: '删除中...' });
			try {
				const res = await this.$request('/addons/qingdong/folder/deleteFile', 'POST', {
					file_id: fileID
				});
				if (res.code === 1) {
					// 修复变量名错误并重新加载数据
					this.currentPage = 1;
					this.fileList = [];
					this.isNoMore = false;
					await this.getFileList();
					uni.showToast({ title: '删除成功' });
				}
			} catch (err) {
				uni.showToast({ title: err.msg, icon: 'none' });
			} finally {
				uni.hideLoading();
			}
		},
		getFileList() {
			console.log('触发加载，当前页码:', this.currentPage, '是否加载中:', this.isLoading, '是否无更多:', this.isNoMore);
			if (this.isLoading || this.isNoMore) return;

			this.isLoading = true;
			uni.showLoading({ title: '加载中', mask: true });

			this.$request('/addons/qingdong/attachment/getCompanyFileList', 'GET', {
				category: this.category,
				page: this.currentPage,
				per_page: 10
			}).then(res => {
				uni.hideLoading();
				const response = res.data;
				if (response.data && response.data.length > 0) {
					// 转换时间戳为可读格式
					const formattedData = response.data.map(item => ({
						...item,
						createtime: this.formatTime(item.createtime),
						filesize: this.formatFileSize(item.filesize)
					}));

					this.fileList = this.currentPage === 1
						? formattedData
						: [...this.fileList, ...formattedData];

					this.totalPages = response.last_page;
					this.isNoMore = this.currentPage >= response.last_page;
					this.currentPage++;
				} else {
					this.isNoMore = true;
					if (this.currentPage === 1) this.fileList = [];
				}
			}).catch(() => {
				this.isNoMore = true;
			}).finally(() => {
				this.isLoading = false;
				uni.hideLoading();
			});
		},
		// 新增时间格式化方法
		formatTime(timestamp) {
			const date = new Date(timestamp * 1000);
			return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} 
            ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
		},

		// 新增文件大小格式化
		formatFileSize(bytes) {
			if (bytes === 0) return '0 B';
			const k = 1024;
			const sizes = ['B', 'KB', 'MB', 'GB'];
			const i = Math.floor(Math.log(bytes) / Math.log(k));
			return `${(bytes / Math.pow(k, i)).toFixed(2)} ${sizes[i]}`;
		},
		// 修改分类切换方法
		handleFileCollection() {
			this.category = '';
			this.currentPage = 1;
			this.fileList = [];
			this.isNoMore = false;
			this.getFileList();
		},
		handleDataLibrary() {
			this.category = 'category1';
			this.currentPage = 1;
			this.fileList = [];
			this.isNoMore = false;
			this.getFileList();
		},
		// 预览文件
		previewFile(url) {
			// 检查文件是否已下载
			uni.showLoading({ title: '正在打开...' });  // 新增加载提示
			uni.downloadFile({
				url: url,
				success: function (res) {
					var filePath = res.tempFilePath;
					uni.openDocument({
						filePath: encodeURI(filePath),
						showMenu: true,
						success: function (res) {
							uni.hideLoading();  // 隐藏加载提示
							console.log('打开文档成功', res);
						},
						fail: function (err) {
							uni.hideLoading();  // 隐藏加载提示
							console.error('打开文档失败', err);
						}
					});
				},
				fail: (err) => {
					uni.hideLoading();  // 隐藏加载提示
					console.error('下载失败', err);
					uni.showToast({ title: '文件下载失败', icon: 'none' });  // 新增失败提示
				}
			});
		},
		// 下载文件
		downloadFile(url) {
			download.downloadFun(url);
		},
		// 去上传按钮点击事件
		uploadFile() {
			const token = uni.getStorageSync('user_token');
			uni.chooseImage({
				count: 9,
				type: 'all',
				success: async (res) => {
					const result = uni.uploadFile({
						url: 'https://hfd.bjlzkj.com/addons/qingdong/common/companyupload',
						filePath: res.tempFilePaths[0],  // 改用tempFilePaths数组中的路径
						name: 'file',  // 后端接收文件的参数名
						formData: {
							category: this.category  // 添加分类参数
						},
						header: {
							'Content-Type': 'application/json',
							'token': token // 新增token请求头
						},
						success: (uploadFileRes) => {
							console.log('上传结果:', uploadFileRes);
							uni.showToast({ title: '上传成功' });
							this.currentPage = 1;
							this.fileList = [];
							this.isNoMore = false;  // 新增重置加载状态
							this.getFileList();  // 确保携带当前分类参数
						},
						fail: (err) => {
							console.error('上传失败:', err);
							uni.showToast({ title: '上传失败', icon: 'none' });
						},
					})
				}
			});
		}
	}
};
</script>

<style scoped lang="scss">
// 在原有样式基础上添加
.loading-text {
	text-align: center;
	padding: 32rpx 0;
	color: #1890ff;
	font-size: 28rpx;
	display: flex;
	align-items: center;
	justify-content: center;

	&::after {
		content: '';
		display: inline-block;
		margin-left: 16rpx;
		width: 28rpx;
		height: 28rpx;
		border: 4rpx solid #1890ff;
		border-radius: 50%;
		border-top-color: transparent;
		animation: rotate 0.8s linear infinite;
	}
}

.no-more-text {
	text-align: center;
	padding: 48rpx 0;
	color: #999;
	font-size: 24rpx;
	position: relative;

	&::before,
	&::after {
		content: '';
		position: absolute;
		top: 50%;
		width: 100rpx;
		height: 1rpx;
		background: #eee;
	}

	&::before {
		left: 20%;
	}

	&::after {
		right: 20%;
	}
}

@keyframes rotate {
	0% {
		transform: rotate(0deg);
	}

	100% {
		transform: rotate(360deg);
	}
}

.file-page {
	display: flex;
	flex-direction: column;
	height: 100vh;
}

/* 顶部功能按钮 */
.toolbar {
	display: flex;
	justify-content: space-around;
	padding: 32rpx;

	.button {
		width: 284rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 8px 16px;
		box-sizing: border-box;
		border-bottom: 10rpx solid #FFBB00;
		border-radius: 6px;
		color: #1890ff;
		background: #fff;
		font-size: 30rpx;
	}
}



.icon {
	width: 48rpx;
	height: 48rpx;
	margin-right: 16rpx;
}

/* 文件列表 */
.file-list {
	flex: 1;
	padding: 32rpx;
	padding-bottom: 120rpx; // 新增底部内边距
	background-color: #f5f5f5; // 新增背景色

	.file-item {
		background-color: white;
		padding: 32rpx;
		border-radius: 16rpx;
		margin-bottom: 32rpx;
		box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);
	}

	.file-name {
		font-size: 20rpx;
		font-weight: bold;
		border-bottom: 1rpx dashed #ccc;
		padding-bottom: 20rpx;
	}

	.folder-icon {
		width: 40rpx;
		height: 40rpx;
		vertical-align: middle;
		margin-right: 16rpx;
	}

	.file-description {
		color: #888;
		line-height: 1.4;
		word-break: break-all;
		margin-top: 8rpx;
		font-size: 24rpx;
	}

	.flex {
		display: flex;
		align-items: center;
		justify-content: space-between;

		.file-time {
			font-size: 20rpx;
			color: #888;
			margin-top: 8rpx;
		}

		.file-actions {
			display: flex;
			margin-top: 16rpx;

			.action1 {
				display: flex;
				align-items: center;
				color: #1890ff;
				background: rgba(0, 118, 222, 0.07);
				margin-right: 16px;
				font-size: 24rpx;
				padding: 10rpx 20rpx;
				border-radius: 24rpx;
			}

			.action2 {
				display: flex;
				align-items: center;
				color: #1890ff;
				background: rgba(0, 185, 93, 0.14);
				margin-right: 16px;
				font-size: 24rpx;
				padding: 10rpx 20rpx;
				border-radius: 24rpx;
			}

			.action-icon {
				width: 26rpx;
				height: 26rpx;
				margin-right: 8rpx;
			}
		}
	}
}
.addimg {
	width: 96rpx;
	height: 96rpx;
	position: fixed;
	bottom: 200rpx;
	right: 40rpx;
}

</style>